package handler

import (
	"car-sys/cache"
	"car-sys/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	/*
		SELECT
		  cars.id AS Cid,
		  car_types.type_name AS TypeName,
		  cars.car_name AS CarName,
		  cars.car_no AS CarNo,
		  cars.car_code AS CarCode,
		  cars.car_price AS CarPrice
		FROM
		  cars
		  LEFT JOIN car_types ON cars.tid = car_types.id

	*/
	var car []models.CarTypeList

	redis_key := "car_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("cars").
			Select(
				"cars.id AS Cid",
				"car_types.type_name AS TypeName",
				"cars.car_name AS CarName",
				"cars.car_no AS CarNo",
				"cars.car_code AS CarCode",
				"cars.car_price AS CarPrice",
			).
			Joins("LEFT JOIN car_types ON cars.tid = car_types.id").
			Offset(offset).Limit(size).Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	var count int64
	models.DB.Model(&models.Car{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  car,
		"count": count,
	})
	return
}
func CarDetail(c *gin.Context) {
	id := c.Query("id")
	var car models.Car
	redis_key := "car_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("cars").
			Select(
				"cars.id AS Cid",
				"car_types.type_name AS TypeName",
				"cars.car_name AS CarName",
				"cars.car_no AS CarNo",
				"cars.car_code AS CarCode",
				"cars.car_price AS CarPrice",
			).
			Joins("LEFT JOIN car_types ON cars.tid = car_types.id").
			Where("cars.id = ?", id).Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": car,
	})
	return
}
